package com.h2.util.image;

import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public final class ImageUtils {
   
   public static final String MIME_TYPE_JPEG = "image/jpeg";

   public static final String MIME_TYPE_PNG = "image/png";

   public static enum ENCODING {
      JPEG, PNG, GIF
   }
   
   private ImageUtils() {
      //utility constructor
   }
   
   public static File writeImage(String fileName, String fileDir,
         ENCODING encoding, RenderedImage rendImage) throws IOException {
      File file = null;
      
      switch (encoding) {
         case JPEG:
            // Save as JPEG
            boolean exists = (new File(fileDir)).exists();
            if (exists) {
               file = new File(fileDir, fileName + ".jpg");
            }
            else {
               new File(fileDir).mkdirs();
               file = new File(fileDir, fileName + ".jpg");
            }
            
            ImageIO.write(rendImage, "jpg", file);
            break;
         case PNG:
            // Save as PNG
            exists = (new File(fileDir)).exists();
            if (exists) {
               file = new File(fileDir, fileName + ".png");
            }
            else {
               new File(fileDir).mkdirs();
               file = new File(fileDir, fileName + ".png");
            }
             ImageIO.write(rendImage, "png", file);
            break;
         case GIF:
            // Save as GIF
            exists = (new File(fileDir)).exists();
            if (exists) {
               file = new File(fileDir, fileName + ".gif");
            }
            else {
               new File(fileDir).mkdirs();
               file = new File(fileDir, fileName + ".gif");
            }
            
            ImageIO.write(rendImage, "gif", file);
            break;
         
         default:
            break;
      }
      return file;
   }
}
